'use strict';

/**
 * @ngdoc directive
 * @name webApp.directive:homeNews
 * @description
 * # homeNews
 */
angular.module('webApp')
  .directive('homeNews', function ($rootScope,cookie,popBox,promiseMore,$filter,$location) {
  return {
    templateUrl: 'views/homeNews.html',
    restrict: 'AE',
    replace: false,
    scope: {
      homeNewsData: '=homeNewsData'
    },
    link: function postLink($scope, element, attrs) {
      //记忆缓存过滤器
      var filter = _.memoize(function(data){
        return $filter('trustHtml',data)
      })();
      $scope.$watch('homeNewsData',function(){
        if($location.path() == '/root/moreReport'){
          $scope.moreShow = false;
        }
        else{
          $scope.moreShow = true;
          if($scope.homeNewsData){
            angular.forEach($scope.homeNewsData,function(obj){
              obj.column_name = filter(obj.column_name);
              angular.forEach(obj.articles,function(obj){
                obj.title = filter(obj.title);
                obj.origin = filter(obj.origin);
              });
            });
          }
        }

      });
      //写入新闻id的cookie
      $scope.setId = function(id){
        cookie.setCookie('newsId',id);
      };
      //写入更多id的cookie
      $scope.moreId = function(id){
        cookie.setCookie('column_id',id);
        promiseMore.moreArticles(id).then(function(data){
          $rootScope.moreTitles = data;
        });
      };
      //收藏
      $scope.collection = function(id){
        if(cookie.getCookie('access_token') && id){
          promiseMore.stars(id).then(function(){
            popBox.showConfirm('提示','收藏成功');
          });
        }
        else{
          popBox.showConfirm('警告','请先登录！');
        }
      };
    }
  };
});
